package main

import (
	"fmt"
	"strings"

	"github.com/lxn/walk"
	"github.com/lxn/win"

	"gitee.com/wmdng/ggui/blethrd"
	_ "gitee.com/wmdng/ggui/manifest"
)

type TermUI struct {
	te *walk.TextEdit
}

func (tui *TermUI) WriteString(s string) (n int, err error) {

	tui.te.Synchronize(func() {
		tui.te.AppendText(s + "\r\n")
	})

	return len(s), nil
}

func main() {
	var tui *TermUI

	fmt.Println("hello")

	/**/
	mw, _ := walk.NewMainWindowWithName("Terminal for BLE")
	vb := walk.NewVBoxLayout()
	vb.SetMargins(walk.Margins{1, 0, 1, 0})
	mw.SetLayout(vb)

	te, _ := walk.NewTextEditWithStyle(mw, win.WS_VSCROLL)
	te.SetText("multi\r\n")
	te.SetReadOnly(true)

	ft, _ := walk.NewFont("Consolas", 12, 0)
	te.SetFont(ft)

	//sbr, _ := walk.NewSolidColorBrush(walk.RGB(120, 135, 156))
	//te.SetBackground(sbr)

	/**/
	tui = new(TermUI)
	tui.te = te
	thrd := blethrd.NewThread(tui)

	/**/
	le, _ := walk.NewLineEdit(mw)
	le.SetText("")
	le.EditingFinished().Attach(func() {
		t := le.Text()
		t = strings.TrimSpace(t)

		if len(t) > 0 {

			if t == "quit" {
				walk.App().Exit(0)
				return
			}

			fmt.Println("finish:", le.Text())
			le.SetText("")
			te.AppendText(">> " + t + "\r\n")

			/* post to bleThread */
			thrd.WriteString(t)
		}
	})

	ft2, _ := walk.NewFont("Consolas", 15, 0)
	le.SetFont(ft2)

	sb := mw.StatusBar()
	sb.SetVisible(true)
	sb.SetAlignment(walk.AlignHFarVCenter)

	sb1 := walk.NewStatusBarItem()
	sb1.SetText("sss1")
	sb.Items().Add(sb1)

	sb2 := walk.NewStatusBarItem()
	sb2.SetText(".....")
	sb.Items().Add(sb2)

	/**/
	mw.Show()
	mw.Run()
}
